<template>
  <div class="regist flex js-ct">
    <div class="box mt-90 flex flex-column js-ct align-center">
      <div class="title text-30 share-color">{{ $t("register.register") }}</div>
      <div class="regist-box radius second-bg">
        <div class="tab text-14 flex js-ct point">
          <div
            class="tab-box text-ellipsis"
            :class="tabid === 1 ? 'tabactive text-t1' : 'text-t2'"
            @click="changeTab(1)"
          >
            {{ $t("register.registerByPhone") }}
          </div>
          <div
            class="tab-box text-ellipsis"
            :class="tabid === 2 ? 'tabactive text-t1' : 'text-t2'"
            @click="changeTab(2)"
          >
            {{ $t("register.registerByEmail") }}
          </div>
        </div>
        <!-- 手机注册 -->
        <el-form
          :model="param"
          :rules="rules"
          ref="ruleForm"
          class="demo-ruleForm"
        >
          <el-form-item
            :prop="tabid === 1 ? 'user_phone_number' : 'user_email'"
            v-show="tabid === 1"
          >
            <div class>
              <selectCountry
                ref="country"
                @inputPhone="inputPhone"
                @selectCountry="selectCountry"
              />
            </div>
          </el-form-item>
          <!-- 邮箱注册 -->
          <el-form-item
            :prop="tabid === 2 ? 'user_email' : 'user_phone_number'"
            v-show="tabid === 2"
          >
            <div class>
              <el-input
                v-model="param.user_email"
                @change="changeEmail"
                :placeholder="$t('login.emailTip')"
              ></el-input>
            </div>
          </el-form-item>
          <!-- <el-form-item prop="verification_code">
            <div class>
              <sendCode
                @inputCode="inputcode"
                :param="codeParam"
                @getKey="getkey"
              />
            </div>
          </el-form-item> -->
          <el-form-item prop="user_password">
            <div style="width:100%;">
              <el-input
                v-model="param.user_password"
                ref="password"
                :type="passwordType"
                :placeholder="$t('login.passwordTip')"
              >
                <template #suffix>
                  <span class="show-pwd" @click="showPwd">
                    <svg-icon
                      :data_iconName="
                        passwordType === 'password' ? 'ic_eye' : 'ic_eye_open'
                      "
                    />
                  </span>
                </template>
              </el-input>
            </div>
          </el-form-item>
          <el-form-item prop="user_confirm_password">
            <div style="width:100%;">
              <el-input
                ref="confirmPassword"
                v-model="param.user_confirm_password"
                :type="confirmPasswordType"
                :placeholder="$t('register.confirmPasswordTip')"
              >
                <template #suffix>
                  <span class="show-pwd" @click="showConfirmPwd">
                    <svg-icon
                      :data_iconName="
                        confirmPasswordType === 'password'
                          ? 'ic_eye'
                          : 'ic_eye_open'
                      "
                    />
                  </span>
                </template>
              </el-input>
            </div>
          </el-form-item>
		  <el-form-item prop="user_pay_password">
		    <div style="width:100%;">
		      <el-input
		        ref="confirmPassword"
		        v-model="param.paypassword"
		        :type="payPasswordType"
		        :placeholder="$t('fiat.enterFundCode')"
		      >
		        <template #suffix>
		          <span class="show-pwd" @click="showPayPwd">
		            <svg-icon
		              :data_iconName="
		                payPasswordType === 'password'
		                  ? 'ic_eye'
		                  : 'ic_eye_open'
		              "
		            />
		          </span>
		        </template>
		      </el-input>
		    </div>
		  </el-form-item>
          <el-form-item
            :prop="isInviteCode ? 'invite_code_required' : 'invite_code'"
          >
            <div style="width:100%;">
              <el-input
                v-if="!isInviteCode"
                v-model="param.invite_code"
                :disabled="isCode"
                :placeholder="
                  isInviteCode
                    ? $t('user.invitecode')
                    : $t('register.invitationCodeTip')
                "
              ></el-input>
              <el-input
                :disabled="isCode"
                v-if="isInviteCode"
                v-model="param.invite_code_required"
                :placeholder="
                  isInviteCode
                    ? $t('user.invitecode')
                    : $t('register.invitationCodeTip')
                "
              ></el-input>
            </div>
          </el-form-item>
          <div class="mb-30 text-left text-14 reg">
            <el-checkbox v-model="isCheck">
              <div class="break-space">
                {{ $t("register.readAndAgree") }}
                <router-link
                  class="text-login"
                  to="/agreement?name=user_protocol"
                  >{{ appName }}{{ $t("footer.userProtocol") }}</router-link
                >
              </div>
            </el-checkbox>
          </div>
          <div class="mb-20">
            <el-button
              style="width:100%;height:46px"
              type="primary"
              @click="submitForm('ruleForm')"
              :disabled="!isCheck"
              class="login-btn"
              >{{ $t("register.register") }}</el-button
            >
          </div>
          <div class="islogin text-center text-14 text-t2">
            {{ $t("register.registered") }}?
            <router-link to="/login" class="text-login text-14 text-bold">{{
              $t("login.login")
            }}</router-link>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import selectCountry from "@/components/selectCountry/SelectCountry.vue";
import sendCode from "@/components/sendCode/SendCode.vue";
import { registerByPhone, registerByEmail } from "@/api/user";
import { ElMessage } from "element-plus";
import { setInviteCode, removeInviteCode, getInviteCode } from "@/utils/auth";
import { PhoneNumberUtil } from "google-libphonenumber";
import countrys from "@/utils/country.js";
import useProtocolSetting from "@/commonapi/useProtocolSetting";
import {
  passwordRule,
  emailRule,
  inviteCodeRule,
  phoneRule,
} from "@/utils/formValidation";
import { useStore } from "vuex";

export default {
  components: { selectCountry, sendCode },
  name: "register",
  data() {
    var Password = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("*" + this.$t("formTip.passwordTip")));
      } else {
        if (!passwordRule.reg.test(value)) {
          callback(new Error("*" + passwordRule.message));
        } else {
          callback();
        }
      }
    };
    var confirmPass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("*" + this.$t("formTip.comfirmPassTip")));
      } else {
        if (this.param.user_password !== value) {
          callback(new Error("*" + this.$t("formTip.passDifTip")));
        } else {
          callback();
        }
      }
    };
	var payPass = (rule, value, callback) => {
	  if (value === "") {
	    callback(new Error("*" + this.$t("fait.enterFundCode")));
	  } else {
	    callback();
	  }
	};
    var Email = (rule, value, callback) => {
      console.log(value);
      if (value === "") {
        callback(new Error("*" + this.$t("formTip.emailTip")));
      } else {
        if (!emailRule.reg.test(value)) {
          callback(new Error("*" + emailRule.message));
        } else {
          callback();
        }
      }
    };
    var PhoneRule = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("*" + this.$t("formTip.phoneTip")));
      } else {
        callback();
        // if (this.codeParam.area_code == "+1809") {
        //   callback();
        // } else {
        //   if (!phoneRule.reg.test(value)) {
        //     callback(new Error("*" + phoneRule.message));
        //   } else {
        //     const phoneUtil = PhoneNumberUtil.getInstance();
        //     let flag = countrys.filter((item) => {
        //       return item["area_code"] === this.codeParam.area_code;
        //     });
        //     const number = phoneUtil.parseAndKeepRawInput(
        //       value,
        //       flag[0].flag.toUpperCase()
        //     );
        //     const isValite = phoneUtil.isValidNumber(number);
        //     if (!isValite) {
        //       callback(new Error("*" + this.$t("formTip.phoneReg")));
        //     } else {
        //       callback();
        //     }
        //   }
        // }
      }
    };
    var inviteCode = (rule, value, callback) => {
      if (value) {
        if (inviteCodeRule.reg.test(value)) {
          callback();
        } else {
          callback(new Error(inviteCodeRule.message));
        }
      } else {
        callback();
      }
    };
    var inviteCodeRequired = (rule, value, callback) => {
      console.log(value);
      if (value) {
        if (inviteCodeRule.reg.test(value)) {
          callback();
        } else {
          callback(new Error(inviteCodeRule.message));
        }
      } else {
        callback(new Error("*" + this.$t("formTip.inviteCodeTip")));
      }
    };
    return {
      isCode: "", //是否是不可更改的邀请码
      clientH: 0,
      appName: window.VUE_APP_NAME,
      passwordType: "password",
      confirmPasswordType: "password",
	  payPasswordType:"password",
      tabid: 1,
      param: {}, //注册数据
      isCheck: false,
      codeParam: { type: "register" },
      isInviteCode: false,
      phone: {},
      rules: {
        user_phone_number: [{ validator: PhoneRule, trigger: "blur" }],
        user_email: [{ validator: Email, trigger: "blur" }],
        verification_code: [
          {
            required: true,
            message: "*" + this.$t("formTip.codeTip"),
            trigger: "blur",
          },
        ],
        user_password: [{ validator: Password, trigger: "blur" }],
        user_confirm_password: [{ validator: confirmPass, trigger: "blur" }],
		user_pay_password: [{ validator: payPass, trigger: "blur" }],
        invite_code: [{ validator: inviteCode, trigger: "blur" }],
        invite_code_required: [
          { validator: inviteCodeRequired, trigger: "blur" },
        ],
      },
      user_protocol: true,
    };
  },
  computed: {
    systemInfo() {
      return this.$store.state.user.systemInfo;
    },
  },
  created() {
    this.clientH = window.innerHeight;
    this.$store = useStore();
    if (this.$store.getters.tab) {
      this.tabid = this.$store.getters.tab;
      console.log(this.tabid);
      this.changeTab(this.tabid);
      if (this.$store.getters.accountReg) {
        if (this.$store.getters.tab === 1) {
          this.inputPhone({
            user_phone_number: this.$store.getters.accountReg,
          });
          let accountReg = this.$store.getters.accountReg;
          this.$nextTick(() => {
            console.log((this.$refs.country.phoneNumber = accountReg));
          });
        } else if (this.$store.getters.tab === 2) {
          this.param.user_email = this.$store.getters.accountReg;
          this.codeParam.user_email = this.$store.getters.accountReg;
        }
      }
    }
    let code = this.$route.query.code || getInviteCode();
    if (code) {
      this.param.invite_code = code;
      this.param.invite_code_required = code;
      this.isCode = true;
      removeInviteCode();
      setInviteCode(code);
      // location.reload();
    } else {
      this.isCode = false;
    }
  },
  mounted() {
    this.getConfig();
    // 获取协议状态
    const { user_protocol } = useProtocolSetting();
    this.user_protocol = user_protocol;
  },
  methods: {
    //邀请码是否必填
    getConfig() {
      this.systemInfo?.forEach((ele) => {
        if (ele.key === "invitation_code_status") {
          this.isInviteCode = ele.value;
        }
      });
    },
    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = "";
      } else {
        this.passwordType = "password";
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      });
    },
    showConfirmPwd() {
      if (this.confirmPasswordType === "password") {
        this.confirmPasswordType = "";
      } else {
        this.confirmPasswordType = "password";
      }
      this.$nextTick(() => {
        this.$refs.confirmPassword.focus();
      });
    },
	showPayPwd() {
	  if (this.payPasswordType === "password") {
	    this.payPasswordType = "";
	  } else {
	    this.payPasswordType = "password";
	  }
	  this.$nextTick(() => {
	    this.$refs.payPasswordType.focus();
	  });
	},
    // 切换手机邮箱注册保留数据
    changeTab(i) {
      this.tabid = i;
      // let param = this.param;
      // this.param = {
      //   invite_code: param.invite_code,
      //   invite_code_required: param.invite_code_required
      // };
      this.codeParam = { type: "register" };
    },
    // 输入邮箱
    changeEmail(value) {
      this.codeParam.email = value;
    },
    // 手机号输入完成
    inputPhone(data) {
      this.param = Object.assign(this.param, data);
      this.codeParam.phone_number = data.user_phone_number;
      this.codeParam.area_code = data.user_area_code;
    },
    // 选择国家
    selectCountry(data) {
      this.param = Object.assign(this.param, data);
      this.codeParam.area_code = data.user_area_code;
    },
    // 输入验证码
    inputcode(code) {
      this.param.verification_code = code;
    },
    // 获取校验的key
    getkey(key) {
      this.param.key = key;
    },
    // 注册
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.isInviteCode) {
            this.param.invite_code = this.param.invite_code_required;
          }
          const requestFun = this.tabid === 1 ? registerByPhone : registerByEmail;
		  let params = {}
          if (this.tabid === 1) {
            this.param.user_email = "";
			params = {
				type: 'mobile',
				account: this.param.user_phone_number,
				password: this.param.user_password,
				re_password: this.param.user_confirm_password,
				sms_code: this.param.verification_code,
				invite_code: this.param.invite_code,
				pay_password: this.param.paypassword,
				area_id: this.param.user_area_code,
			};
          } else {
            this.param.user_phone = "";
			params = {
				type: 'email',
				account: this.param.user_email,
				password: this.param.user_password,
				re_password: this.param.user_confirm_password,
				sms_code: this.param.verification_code,
				invite_code: this.param.invite_code,
				pay_password: this.param.paypassword,
			};
          }
          requestFun(params).then((res) => {
            if (res.code == 1) {
              ElMessage.success(this.$t("assets.success"));
              this.$router.push("/login");
            }else{
				ElMessage.success(this.$t("assets.fail"));
			}
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.break-space {
  white-space: break-spaces;
}
.mb-20 {
  margin-bottom: 20px;
}
.mb-30 {
  margin-bottom: 30px;
}
.mt-90 {
  margin-top: 90px;
}
.regist {
  width: 100%;
  min-height: calc(100% - 60px);
  height: 900px;
  position: absolute;
  top: 60px;
  left: 0;
  background-image: url("../assets/theme1/loginbg.png");
  background-repeat: no-repeat;
  background-size: 100% 100%;
  min-height: 800px;
  padding-bottom: 10px;
}
.regist-box {
  width: 400px;
  padding: 30px;
  box-sizing: border-box;
}
.islogin {
  margin-bottom: 10px;
}
.title {
  font-family: PingFang SC;
  margin-bottom: 40px;
  font-style: Semibold;
}
.tab {
  line-height: 40px;
  min-height: 40px;
  margin-bottom: 20px;
  text-align: start;
}
.phone {
  margin-inline-end: 30px;
}
.tabactive {
  position: relative;
  font-weight: bold;
  font-family: PingFang SC;
  font-style: Semibold;
  background: @tab-active;
}
.tab-box {
  width: 170px;
  height: 40px;
  text-align: center;
  border-radius: 4px;
  padding: 0 4px;
}
// .tabactive::after {
//   content: "";
//   position: absolute;
//   bottom: 0;
//   left: 0;
//   width: 44px;
//   height: 4px;
//   background: @login-dark;
//   border-radius: 4px;
// }
/deep/.el-checkbox__input.is-checked .el-checkbox__inner {
  background-color: @blue;
  border-color: @blue;
}
/deep/.el-checkbox__input.is-checked + .el-checkbox__label {
  color: @font_42;
}
.reg /deep/.el-checkbox {
  display: flex;
  align-items: center;
}

/deep/ .el-form-item__error{
	top:0 !important;
}
</style>
